package com.hmdp.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
@Slf4j
public class RedisIdWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final long BEGIN_TIMESTAMP = 1640995200L;  // 起始时间戳
    private static final int COUNT_BITS = 32;  // 序列号位数

    public long nextId(String keyPrefix){
        // keyPrefix 用于前缀区分不同业务
        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond-BEGIN_TIMESTAMP;
        // 生成序列号
        String nowDate = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + nowDate);
        // 位运算
        // 拼接并返回
        return timestamp << COUNT_BITS | increment; // 时间戳左移32位，并且和序列号或运算
    }

    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("second =" + second);
    }
}
